package com.firesys.lgoin.ui;



import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import net.tsz.afinal.FinalHttp;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.firesys.R;
import com.firesys.dbhelper.DBOpenHelper;
import com.firesys.dbhelper.DbTableName;
import com.firesys.dbhelper.SharedPreferenceUtil;
import com.firesys.dbhelper.XmlNameHelper;
import com.firesys.httpserver.HttpClientServer;
import com.firesys.httpserver.RequestUrl;
import com.firesys.lgoin.db.LoginDao;
import com.firesys.util.DateUtil;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;


/**
 * 登录
 * @author Administrator
 *
 */
public class LoginActivity extends Activity implements BDLocationListener{

	private EditText mUser; // 帐号编辑框
	private EditText mPassword; // 密码编辑框
	private FinalHttp  http;
	public LocationClient client;
	public Double  latitude;
	public Double  longtude;
	
	public long time;
	public boolean isStart=false;
	  public String status;
	
	 public ProgressDialog pd;
	 public SharedPreferenceUtil sh;
	 public LoginDao  dao;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);
		initLocation();
		sh=new SharedPreferenceUtil(this);
		
		if(sh.getBoolean(XmlNameHelper.CHECKSERVERCONNECT)&&sh.getBoolean(XmlNameHelper.workstatus)){
		    dao=new LoginDao(this, sh.getValue(XmlNameHelper.SqliteName));
		    if(!dao.isaddDeviceitem()){
			    initDate();
			}
		}
		  mUser = (EditText)findViewById(R.id.login_user_edit);
	     mPassword = (EditText)findViewById(R.id.login_passwd_edit);
	     http=new FinalHttp();
	     
	     
	}
	
	public void initLocation(){
		client=new LocationClient(this);
		LocationClientOption option = new LocationClientOption();
		// 打开GPS
		option.setOpenGps(true);
		// 设置坐标类型
		option.setCoorType("bd09ll");
		
	    option.setAddrType("all");

		// 设置网络优先
		
	       option.setPriority(LocationClientOption.NetWorkFirst);
		// 设置产品线名称
		option.setProdName("waterSys");
		option.setScanSpan(5000);
		// 是否启用缓存定位
		option.disableCache(true);
		client.setLocOption(option);
		client.registerLocationListener(this);
		
	  }
	/**
	 * 登录处理
	 * @param view
	 */
	public void login_pw(View v){

    	 if("".equals(mUser.getText().toString()) || "".equals(mPassword.getText().toString()))   //判断 帐号和密码
        {
        	new AlertDialog.Builder(LoginActivity.this)
			.setIcon(getResources().getDrawable(R.drawable.login_error_icon))
			.setTitle("登录错误")
			.setMessage("帐号或者密码不能为空，\n请输入后再登录！")
			.create().show();
         }
        else{
        	
            pd=new ProgressDialog(this);
            pd.setMessage("正在登录");
            pd.show();
            client.start();	
            isStart=true;
            status="登录";
            intiRequest();
        	
        }
    	
    	//登录按钮
    	/*
      	Intent intent = new Intent();
		intent.setClass(Login.this,Whatsnew.class);
		startActivity(intent);
		Toast.makeText(getApplicationContext(), "登录成功", Toast.LENGTH_SHORT).show();
		this.finish();*/
      
	}
	
	
	
	
	
	
	
	
	
	
	
	@Override
	protected void onDestroy() {
		if(dao!=null){
			dao.close();
		}
		super.onDestroy();
	}


	@Override
	public void onReceiveLocation(BDLocation location) {
		if(location!=null){
			 this.latitude=location.getLatitude();
			 this.longtude=location.getLongitude();
			 System.out.println(location.getCity()+"--------------");
		}
		   
		
	}


	@Override
	public void onReceivePoi(BDLocation arg0) {
		// TODO Auto-generated method stub
		
	}
	
	//发起请求
	public void intiRequest(){
		  time=System.currentTimeMillis();
		         latitude=0.0;
		         longtude=0.0;
		         isStart=true;
		         new Thread(){

			    @Override
			    public void run() {
				while(isStart){
				           if(latitude>0){
				               isStart=false;
				               Work();
				           }
				           try {
					    Thread.sleep(500);
					    if((System.currentTimeMillis()-time)>5000&&isStart){
						isStart=false;
						 Work();
					    }
					} catch (InterruptedException e) {
					   
					    e.printStackTrace();
					}
					super.run();
				    
				}
			    }
		             
		         }.start();
	}

	
	//上下班发起的请求
	public String Work( ){

		System.out.println("------发起请求---1111111-----");
		Map<String, String> map=new HashMap<String, String>();
		if(status.equals("登录")){
		    map.put("name", mUser.getEditableText().toString());
		    map.put("pass", mPassword.getEditableText().toString());
		}else{
		    map.put("name", sh.getValue(XmlNameHelper.userName));
		    map.put("pass",sh.getValue(XmlNameHelper.userPASS) );
		}
		
		
	    
		map.put("latitude",latitude+"");
		map.put("longitude", longtude+"");
		map.put("status", status);
		map.put("imsi", sh.getValue(XmlNameHelper.IMEI));
		//map.put("copyerId", sh.getValue(XmlNameHelper.userID));
		map.put("date", DateUtil.getBeforeDay(0));
		HttpClientServer server=new HttpClientServer(LoginActivity.this);
		//String respones=server.doPost(map, RequestUrl.USERLOGIN,true);
		String respones=server.doPost(map, RequestUrl.USERLOGIN,true);
		JSONObject json = null;
		String mess="";	
		System.out.println("-------------respones------------"+respones);
		if(respones.equals("error")){
		        
		        Message msg=myHandler.obtainMessage();
			 msg.what=0;
			myHandler.sendMessage(msg);
			
			
		}else{
		    try {
			json=new JSONObject(respones);
			mess=json.getString("message");
		
			
		    } catch (JSONException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		    }
		    if(!mess.equals("yes")){
	            Message msg=myHandler.obtainMessage();
			msg.what=8;
			msg.obj=mess;
			myHandler.sendMessage(msg);
	       }else{

		try {
		    
		    String message=json.getString("message");
		    if(message.equals("null")){
			Message msg=myHandler.obtainMessage();
			msg.what=1;
			myHandler.sendMessage(msg);
		    }else {
			if(status.equals("登录")){
			    sh.insertValue(XmlNameHelper.workstatus, true);
			    sh.insertValue(XmlNameHelper.userName, mUser.getEditableText().toString());
			    sh.insertValue(XmlNameHelper.userPASS, mPassword.getEditableText().toString());
			    sh.insertValue(XmlNameHelper.userID, json.getString("cpId"));
			    String sqliteName="water_"+sh.getValue(XmlNameHelper.userID)+".db";
			    sh.insertValue(XmlNameHelper.SqliteName, sqliteName);
			    DBOpenHelper helper = new DBOpenHelper(LoginActivity.this,sqliteName);
			    SQLiteDatabase db = helper.getReadableDatabase();
			    db.close();
			    if(dao==null){
			    	dao=new LoginDao(this, sqliteName);
			    }
			    if(!dao.isaddDeviceitem()){
				    initDate();
				}
			    Message msg=myHandler.obtainMessage();
			    msg.what=2;
			    myHandler.sendMessage(msg);
			  
			}else if(status.equals("注销")){
			    sh.insertValue(XmlNameHelper.workstatus, false);			  
			    sh.insertValue(XmlNameHelper.userID,"");			   
			    sh.insertValue(XmlNameHelper.SqliteName, "");
			   
			    Message msg=myHandler.obtainMessage();
			    msg.what=5;
			    myHandler.sendMessage(msg);
			}
		    }
		} catch (JSONException e) {
		  
		    e.printStackTrace();
		}

		}
		    
		}
		

		return null;
	}
	Handler myHandler=new Handler(){

		@Override
		public void handleMessage(Message msg) {
		     if(msg.what==1){		
		         client.stop();
		         pd.dismiss();
		         new AlertDialog.Builder(LoginActivity.this)
					.setIcon(getResources().getDrawable(R.drawable.login_error_icon))
					.setTitle("登录失败")
					.setMessage("帐号或者密码不正确，\n请检查后重新输入！")
					.create().show();
		     }else if(msg.what==2){
			 pd.dismiss();
		         client.stop();
			 Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
			 sh.insertValue(XmlNameHelper.UnlockStatus, true);
			// Response();
		     }else if(msg.what==3){
			
		     }else if(msg.what==4){
			
		     }else if(msg.what==5){
			 sh.insertValue(XmlNameHelper.UnlockStatus, false);
			 pd.dismiss();
			 client.stop();
//			 Intent intent=new Intent("com.app.exit");
//			       sendBroadcast(intent);
			 setResult(RESULT_OK);
			       finish();
		     }else if(msg.what==7){
			
			 setResult(RESULT_OK);
			 finish();
		     }else if(msg.what==0){
			    isStart=false;
			  client.stop();
			   pd.dismiss();
			   new AlertDialog.Builder(LoginActivity.this)
				.setIcon(getResources().getDrawable(R.drawable.login_error_icon))
				.setTitle("登录失败")
				.setMessage("与服务器连接发生错误 ！")
				.create().show();
		     }else if(msg.what==8){
			   isStart=false;
			   client.stop();
			   pd.dismiss();
			   sh.insertValue(XmlNameHelper.GPSLATITUDE, "0.0");
			   sh.insertValue(XmlNameHelper.GPSLONGITUDE, "0.0");
			   sh.insertValue(XmlNameHelper.GPSDATE, "0");
		           Toast.makeText(LoginActivity.this, msg.obj.toString(), Toast.LENGTH_SHORT).show();
		     }
		    super.handleMessage(msg);
		}
		
	};

	
	//初始化巡检类型
	public void initDate(){
		
		 String respon=getFromAssets();
		
		 if(!respon.equals("error")){
		     try {
			JSONObject  json=new JSONObject(respon);
			JSONArray  item=json.getJSONArray("item");
			JSONArray  subitem=json.getJSONArray("subitem");
			List<ContentValues> itemlist=new ArrayList<ContentValues>();
			List<ContentValues> sublist=new ArrayList<ContentValues>();
			for(int i=0;i<item.length();i++){
			    JSONObject jb=item.getJSONObject(i);
			    ContentValues value=new ContentValues();
			    value.put("number", jb.getString("deviceItemNumber"));
			    value.put("name", jb.getString("deviceItemName"));
			    value.put("forcedpictures", jb.getString("deviceItemType"));
			    value.put("type", jb.getString("deviceItemType"));
			    itemlist.add(value);
			}
			for(int i=0;i<subitem.length();i++){
			    JSONObject jb=subitem.getJSONObject(i);
			    ContentValues value=new ContentValues();
			    value.put("number", jb.getString("number"));
			    value.put("name", jb.getString("name"));
			    value.put("itemNumber", jb.getString("deviceItemNumbeer"));
			  
			    sublist.add(value);
			}
			LoginDao dao=new LoginDao(this, sh.getValue(XmlNameHelper.SqliteName));
			dao.insertALL(sublist, DbTableName.DEVICESUBITEM);
			boolean b=dao.insertALL(itemlist, DbTableName.DEVICEITEM);
			
		    } catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		    }
		     
		 }
		
	}
	//读取assets下文件流
	public String getFromAssets(){
		InputStreamReader inputReader=null;
		 BufferedReader bufReader =null;
		  String line="";
	      String Result="";
		try {
		     inputReader = new InputStreamReader( getResources().getAssets().open("devicejson.text") );
		     bufReader = new BufferedReader(inputReader);
	      
	        while((line = bufReader.readLine()) != null){
	    	   Result += line;
	        }
		} catch (IOException e) {
		    System.out.println("---  e.printStackTrace();------");
		    e.printStackTrace();
		}finally{
		    if(bufReader!=null){
			try {
			    bufReader.close();
			} catch (IOException e) {
			 
			    e.printStackTrace();
			}
		    }
		    if(inputReader!=null){
			try {
			    inputReader.close();
			} catch (IOException e) {
			 
			    e.printStackTrace();
			}
		    }
		} 

		return Result;
		
	}
	
	
}
